<?php

namespace App\Services;

use App\Libs\Verify\src\Captcha;

class Verify
{

    /**
     * 输出验证码
     */
    public static function entry($param = [], $api = false)
    {
        $length = 4;
        if (isset($param['length']) && intval($param['length']) > 2) {
            $length = intval($param['length']);
        }
        // 设置验证码字符库
        $code_set = '';
        if (!empty($param['charset'])) {
            $mletters = str_split($param['charset']);
            $mletters = array_unique($mletters);
            if (count($mletters) > 5) {
                $code_set = trim($param['charset']);
            }
        }
        $use_noise = 1;
        if (isset($param['use_noise'])) {
            $use_noise = intval($param['use_noise']);
        }
        $use_curve = 0;
        if (isset($param['use_curve'])) {
            $use_curve = intval($param['use_curve']);
        }
        $font_size = 25;
        if (isset($param['font_size']) && intval($param['font_size'])) {
            $font_size = intval($param['font_size']);
        }
        $width = 0;
        if (isset($param['width']) && intval($param['width'])) {
            $width = intval($param['width']);
        }
        $height = 0;
        if (isset($param['height']) && intval($param['height'])) {
            $height = intval($param['height']);
        }

        $background = array(243, 251, 254);
        if (isset($param['background'])) {
            $mbackground = array_map('intval', explode(',', $param['background']));
            if (count($mbackground) > 2 && $mbackground[0] <= 255 && $mbackground[1] <= 255 && $mbackground[2] <= 255) {
                $background = [$mbackground[0], $mbackground[1], $mbackground[2]];
            }
        }

        $config = [
            'codeSet' => !empty($code_set) ? $code_set : '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY', // 验证码字符集合
            'expire' => 1800, // 验证码过期时间（s）
            'useImgBg' => false, // 使用背景图片
            'fontSize' => !empty($font_size) ? $font_size : 25, // 验证码字体大小(px)
            'useCurve' => $use_curve === 0 ? false : true, // 是否画混淆曲线
            'useNoise' => $use_noise === 0 ? false : true, // 是否添加杂点
            'imageH' => $height,  // 验证码图片高度
            'imageW' => $width, // 验证码图片宽度
            'length' => !empty($length) ? $length : 4, // 验证码位数
            'bg' => $background, // 背景颜色
            'reset' => true, // 验证成功后是否重置
            'math' => true,
            'api' => $param['api'] ?? false
        ];

        $captcga = new Captcha();
        return $captcga->create($config);
    }

    /**
     * 验证验证码
     */
    public static function check($code, $key = '')
    {
        $captcga = new Captcha();
        return $captcga->check($code, $key);
    }
}
